<template>
    <div id="rx-form-container">
        <template v-if="localData.length==1">
            <div class="previewBox">
                <x-form-build
                    :ref="'rxForm_'+localData[0].alias"
                    :form-data="localData[0].formData"
                    :form-config="localData[0].formConfig"
                    :global-config="localData[0].globalConfig"
                    :form-js="localData[0].formJs"
                    :readOnly="readonly"
                    :printReadonly="printReadonly"
                    :contextData="localData[0].contextData"
                    :permission="localData[0].permission"
                    :alias="localData[0].alias"
                    :name="localData[0].title"
                    :dialogBox="dialogBox"
                    :id-field="localData[0].idField"
                >
                </x-form-build>
            </div>
        </template>
        <template v-else-if="localData.length>1">
            <a-tabs>
                <a-tab-pane v-for="item in localData" :tab="item.title" :forceRender="true" :key="item.alias">
                    <div class="rxContent">
                        <div class="previewBox">
                            <x-form-build
                                :ref="'rxForm_'+item.alias"
                                :form-data="item.formData"
                                :form-config="item.formConfig"
                                :global-config="item.globalConfig"
                                :form-js="item.formJs"
                                :readOnly="readonly"
                                :printReadonly="printReadonly"
                                :contextData="item.contextData"
                                :permission="item.permission"
                                :alias="item.alias"
                                :name="item.title"
                                :dialogBox="dialogBox"
                                :id-field="item.idField"
                            >
                            </x-form-build>
                        </div>
                    </div>
                </a-tab-pane>
            </a-tabs>
        </template>
        <div v-else>
            <div class="loadInfo">
                <div class="loadInfolist">
                    <a-spin size="large"/>
                </div>
                {{ i18n('msa.loading', '亲，系统正在加载单据，请稍候...') }}
            </div>
        </div>
    </div>
</template>

<script>

import DialogBox from "@/assets/js/dialogBox";

export default {
    name: "rx-forms",
    data() {
        return {
            currentAlias: "",
            dialogBox: DialogBox,
            localData: [],
            readonly: false,
            printReadonly: false,//打印只读
            //表单实例
        }
    },
    created() {
    },
    methods: {
        i18n(name, text, key) {
            return this.$ti18(name, text, "BpmInstFormOperat", key);
        },
        /*
        数据结构。
        [{
          name:"表单名称",
          alias:"别名",
          data:{

          }
        }]

        contextData:{
          curUserId:"",
          curUserName:"",
          nodeId:"",
          instId:"",
          defId:"",
          taskId:"",
          opinionHistorys:""  //审批意见历史
        }
         */
        setData(aryData, readonly, contextData, printReadonly) {
            if (!aryData) {
                return;
            }
            this.localData = aryData.map(item => {
                return {
                    formJs: item.script,
                    formConfig: item.metadata ? JSON.parse(item.metadata) : "",
                    globalConfig: item.globalConfig ? JSON.parse(item.globalConfig) : {},
                    permission: item.permission,
                    contextData: contextData,
                    formData: item.data,
                    alias: item.alias,
                    title: item.title,
                    opinionSetting: item.opinionSetting,
                }
            });
            if (this.localData.length > 0) {
                this.currentAlias = this.localData[0].alias;
            }
            this.readonly = readonly;
            this.printReadonly = printReadonly;
        },
        getFormRef(key) {
            if (!key && this.localData.length == 1) {
                let formKey = "rxForm_" + this.localData[0].alias;
                return this.$refs[formKey];
            }
            var ref = (this.localData.length == 1) ? this.$refs[key] : this.$refs[key][0];
            return ref;
        },

        getData() {
            let rtn = {};
            for (var i = 0; i < this.localData.length; i++) {
                let formData = this.localData[i];
                let alias = formData.alias;
                let vm = this.$refs['rxForm_' + formData.alias];
                if (Array.isArray(vm)) {
                    vm = vm[0];
                }
                if (vm) {
                    rtn[alias] = vm.getData();
                }
            }
            return rtn;
        },
        getMetadata() {
            let rtn = {};
            for (var i = 0; i < this.localData.length; i++) {
                let formData = this.localData[i];
                let alias = formData.alias;
                let vm = this.$refs['rxForm_' + formData.alias];
                if (Array.isArray(vm)) {
                    vm = vm[0];
                }
                rtn[alias] = vm.metadata;
            }
            return rtn;
        },
        /**
         * 获取当前节点可用的意见名称。
         */
        getOpinionName() {
            let opinionName = "";
            for (var i = 0; i < this.localData.length; i++) {
                var config = this.localData[i];
                if (config.opinionSetting) {
                    for (var j = 0; j < config.opinionSetting.length; j++) {
                        if (config.opinionSetting[j].setOpinion) {
                            opinionName = config.opinionSetting[j].name;
                            break;
                        }
                    }
                }
            }
            return opinionName;
        },
        getDataByKey(key) {
            for (var i = 0; i < this.localData.length; i++) {
                var formData = this.localData[i];
                var alias = formData.alias;
                if (key == alias) {
                    return formData;
                }
            }
            return {};
        },
        getFormKey(alias) {
            var key = "rxForm_" + alias;
            return key;
        },
        getCurrentForm() {
            return this.getFormRef(this.getFormKey(this.currentAlias));
        },
        /**
         * 设置表单只读。
         * @param readonly
         */
        setReadonly(readonly) {
            for (var i = 0; i < this.localData.length; i++) {
                var formData = this.localData[i];
                var alias = formData.alias;
                var key = this.getFormKey(alias);
                var ref = this.getFormRef(key);
                ref.setReadonly(readonly);
            }
        },
        afterSubmit(result, formJson) {
            var rxForms = this.$refs;
            for (var formKey in rxForms) {
                let form = rxForms[formKey];
                if (form instanceof Array) {
                    form = form[0]
                }
                if (formKey.startsWith("rxForm_") && form && form.$refs.XForm) {
                    if (form.$refs.XForm._afterSubmit) {
                        form.$refs.XForm._afterSubmit(result, formJson);
                    }
                }
            }
        },
        //validRequired:必填校验  validType类型校验
        async valid(validRequired, action) {
            let rxForms = this.$refs;
            for (let formKey in rxForms) {
                let form = rxForms[formKey];
                if (form instanceof Array) {
                    form = form[0]
                }
                if (form && form.$refs.XForm && formKey.startsWith("rxForm_")) {
                  let validResult= {success:true,msg:""};
                  try{
                    validResult= await form.$refs.XForm.valid(validRequired, action)
                  }
                  catch (e){
                    validResult= e;
                  }
                  if (validResult && !validResult.success ) {
                    this.$message.warning((validResult && validResult.msg));
                    return validResult;
                  }
                }
            }
            return {success: true}
        },
        /**
         * 执行表单的方法。
         * @param method
         * @param data
         */
        executeMethod(method, data) {
            let rxForm;
            if (this.localData.length == 1) {
                let alias = this.localData[0].alias;
                rxForm = this.$refs['rxForm_' + alias];
            } else {
                if (method.indexOf(".") == -1) {
                    this.$message.warn(this.i18n("msa.format","方法名需要为表单名.方法名格式"));
                    return;
                }
                let ary = method.split(".");
                let alias = ary[0];
                method = ary[1];
                rxForm = this.$refs['rxForm_' + alias];
            }

            if (!rxForm) {
                this.$message.warn("没有找到表单!");
                return;
            }
            let func = rxForm.$refs.XForm[method];
            if (!func) {
                this.$message.warn(this.i18n("msa.configFunction","请在当前组件中配置方法:") + method);
                return;
            }
            if (data) {
                func(data);
            } else {
                func();
            }
        }
    }
}
</script>

<style scoped>
.loadInfo {
    padding: 5px;
    text-align: center;
    margin: auto;
    width: 350px;
}
#rx-form-container{
    height: inherit;
}
#rx-form-container >>> .table-form {
    width: calc(100% - 2px) !important;
}
.previewBox{
    height: inherit;
    padding-top:1px;
    box-sizing: border-box;
}
</style>

